# -*- coding: utf-8 -*-            
# @Time : 2023/3/31 9:52
# @FileName: im_test.py
# @Software: PyCharm
# @Author: zhou chen
import os
import sys
import json
import time
import uuid
import socket
import struct
import sqlite3
import threading
import asyncio
import configparser
import multiprocessing
from configparser import ConfigParser
from multiprocessing import Process
from socket import setdefaulttimeout

if sys.platform == "win32" or sys.platform == "win64":
    from im_main.handle_log import logger
    from im_main.handle_md import handle_file
    from im_main.linux_all import send_file_to_target
    from im_main.handle_snowflake import worker

else:
    sys.path.append("..")
    from handle_log import logger
    from handle_md import handle_file
    from linux_all import send_file_to_target
    from handle_snowflake import worker
try:
    import requests
    import flask
except ImportError:
    if sys.platform == "win32" or sys.platform == "win64":
        os.system("pip install -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com " + "requests==2.0.0")
        os.system("pip install -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com " + "flask==2.3.2")
    else:
        os.system("pip3 install -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com " + "requests==2.0.0")
        os.system("pip3 install -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com " + "flask==2.2.3")
    import requests
    import flask

# # 所有socket 连接设置五十秒超时
setdefaulttimeout(1)
if sys.platform == "win32" or sys.platform == "win64":
    # 获取当前项目的目录
    project_path = os.path.dirname(os.getcwd())
else:
    project_path = os.path.abspath("..")


class HandleUser(object):
    def __init__(self, url):
        self.conn = requests.session()
        self.url = url
        self.header = {"Accept": "*/*"}

    def send_post(self, api, data):
        try:
            res = self.conn.post(self.url + api, json=data, headers=self.header)
            if res.status_code == 200:
                return json.loads(res.text)
            else:
                logger.error(json.loads(res.text))
                return None
        except requests.exceptions.ConnectionError:
            logger.error("连接错误 网站无法打开")
            return None

    def send_get(self, api):
        try:
            res = self.conn.get(self.url + api, headers=self.header)
            if res.status_code == 200:
                return json.loads(res.text)
            else:
                logger.error(json.loads(res.text))
                return None
        except requests.exceptions.ConnectionError:
            logger.error("连接错误 网站无法打开")
            return None

    def create_header(self, app_id, app_secret, token):
        """
        登录用户端需要的关键信息
        :param app_id: 应用id
        :param app_secret: app 密钥
        :param token: 登录用户端的token
        :return: None
        """
        self.header["appId"] = app_id
        self.header["appSecret"] = app_secret
        self.header["token"] = token

    # 注册用户
    def res_uer(self, app_id, app_secret, merchant_id):
        api = "/v1/merchant/user/thridRegister"
        pin = ''.join(str(uuid.uuid4()).split('-'))
        data = {
            "appId": app_id,
            "appSecret": app_secret,
            "avatar": "avatar",
            "createPerson": "string",
            "extInfo": "string",
            "merchantId": merchant_id,
            "nickname": "test user",
            "pin": pin,
            "sex": True}
        res = self.send_post(api, data)
        return res

    # 商户用户注册
    def res_user_new(self, iphone):
        api = "/register"
        data = {
            "loginName": str(iphone),
            "password": "123456",
            "password2": "123456",
            "nickName": str(iphone)
        }
        res = self.send_post(api, data)
        return res

    # 登录
    def login(self, app_id, app_secret, merchant_id, pin):
        api = "/v1/merchant/user/thridLogin"
        data = {
            "appId": app_id,
            "appSecret": app_secret,
            "createPerson": "string",
            "merchantId": merchant_id,
            "nickname": "string",
            "pin": pin,
            "sex": True
        }
        res = self.send_post(api, data)
        return res

    # 添加好友
    def add_friend(self, app_id, acc_id, apply_acc_id):
        """
        :param app_id:
        :param acc_id: 申请人的pin
        :param apply_acc_id: 对方的 pin
        :return:
        """
        api = "/v1/im-sdk/friend/applyFriend"
        data = {
            "accid": acc_id,  # 申请人的pin
            "aid": app_id,
            "applyAccid": apply_acc_id  # 被申请申请人的 pin

        }
        res = self.send_post(api, data)
        return res

    # 更新好友申请
    def update_agree(self, acc_id, apply_acc_id):
        api = "/v1/im-sdk/friend/updateAgreeStatus"
        data = {
            "accid": acc_id,  # 处理申请的 pin(被申请人的 pin)
            "appyId": apply_acc_id,  # 申请人的pin
            "isPass": True,
            "remark": "添加好友"
        }
        res = self.send_post(api, data)
        return res

    # 创建会话
    def create_chat(self, apply_acc_id):
        api = "/v1/im-sdk/chat/create"
        data = {
            "fpin": apply_acc_id
        }
        res = self.send_post(api, data)
        return res

    # 创建群
    def create_team(self, acc_id, chat_group_type, apply_acc_id_list: list):
        api = "/v1/im-sdk/team/create"
        data = {
            "accid": acc_id,
            "announce": "string",
            "chatGroupType": chat_group_type,
            "forbidFriend": True,
            "icon": "string",
            "inviteAble": True,
            "members": apply_acc_id_list,
            "notice": True,
            "teamName": "测试普通群",
            "visible": True
        }
        res = self.send_post(api, data)
        return res

    # 添加群成员
    def add_team_member(self, acc_id, apply_acc_id_list: list):
        api = "/v1/im-sdk/team/saveBatch"
        data = {
            "accid": acc_id,
            "accids": apply_acc_id_list,
            "tid": "string"
        }
        res = self.send_post(api, data)
        return res

    # 更新群
    def update_team(self, acc_id, icon, tid, chat_group_type,
                    forbid_friend=True, invite_able=True, notice=True, visible=True):
        api = "/v1/im-sdk/team/updateTeam"
        data = {
            "accid": acc_id,
            "announce": "string",
            "chatGroupType": chat_group_type,
            "forbidFriend": forbid_friend,
            "icon": icon,
            "inviteAble": invite_able,
            "notice": notice,
            "teamName": "测试群",
            "tid": tid,
            "visible": visible
        }
        res = self.send_post(api, data)
        return res

    # 踢出群聊
    def delete_batch(self, apply_acc_id_list, tid):
        api = "/v1/im-sdk/team/deleteBatch"
        data = {
            "accids": apply_acc_id_list,
            "tid": tid  # 群id
        }
        res = self.send_post(api, data)
        return res

    # 群禁言
    def team_silence(self, tid):
        api = "/v1/im-sdk/team/silence"
        data = {
            "switched": True,
            "tid": tid
        }
        res = self.send_post(api, data)
        return res

    # 设置群为可以邀请状态
    def team_invite_able(self, tid, switched=True):
        api = "/v1/im-sdk/team/inviteAble"
        data = {
            "switched": switched,
            "tid": tid
        }
        res = self.send_post(api, data)
        return res

    # 移除群
    def team_remove(self, apply_acc_id_list, tid):
        api = "/v1/im-sdk/team/remove"
        data = {
            "members": apply_acc_id_list,
            "tid": tid
        }
        res = self.send_post(api, data)
        return res


class HandleConfig(object):
    def __init__(self, file_name, config_path="/config/"):
        self._cf = ConfigParser()
        # 配置文件的位置， 需要将配置文件放在指定的文件夹下
        self._path = project_path + config_path + file_name
        logger.info(self._path)
        self._cf.read(self._path, encoding="utf8")

    # 保存配置文件
    def write_cf(self):
        with open(self._path, "w+") as f:
            self._cf.write(f)

    # 获取 配置文件的 section
    def get_section(self):
        return self._cf.sections()

    # 增加 配置文件 section
    def add_section(self, section):
        self._cf.add_section(section)
        self.write_cf()

    # 存储或修改对应 option 的值
    def set_value(self, section, option, value):
        self._cf.set(section, option, value=value)
        self.write_cf()

    # 获取对应option的值
    def get_value(self, section, option):
        return self._cf.get(section, option)

    # 获取section下的 option
    def get_options(self, section):
        return self._cf.options(section)


class HandleSql(object):
    def __init__(self, database):
        self.db = sqlite3.connect(database, timeout=20)
        self.conn = self.db.cursor()

    # 插入数据
    def insert(self, sql):
        try:
            self.conn.execute(sql)
            self.db.commit()
        except Exception as err:
            logger.error("数据插入异常！%s" % err)
            return None

    # 查询数据
    def select(self, sql):
        try:
            self.conn.execute(sql)
            return self.conn.fetchall()
        except Exception as err:
            logger.error("查询出现错误！%s" % err)
            return None


class MyThreading(threading.Thread):
    # 重写线程，可以获取返回值
    def __init__(self, func, args=()):
        super(MyThreading, self).__init__()
        self.func = func
        self.args = args
        self.result = ""

    def run(self):
        self.result = self.func(*self.args)

    def get_result(self):
        threading.Thread.join(self)
        try:
            return self.result
        except Exception as err:
            logger.error(err)
            return None


# 创建表格
def create_user_table(database):
    handle_sql = HandleSql(database)
    table_name = handle_sql.select("SELECT name from sqlite_master where type='table' order by name")
    if ("user_data",) not in table_name:
        # group_id， super_group_id以列表的形式存储
        sql = "CREATE TABLE user_data(" \
              "id INTEGER PRIMARY KEY AUTOINCREMENT," \
              "pin VARCHAR(60) NOT NULL," \
              "token VARCHAR(600) NOT NULL," \
              "phone VARCHAR(60)" \
              ");"
        handle_sql.insert(sql)
    handle_sql.db.close()


# 创建会话表格
def create_message_chat_table(database):
    handle_sql = HandleSql(database)
    table_name = handle_sql.select("SELECT name from sqlite_master where type='table' order by name")
    if ("message_chat",) not in table_name:
        sql = "CREATE TABLE message_chat(" \
              "chat_id VARCHAR(60) NOT NULL," \
              "pin VARCHAR(60) NOT NULL," \
              "apply_acc_id VARCHAR(60) NOT NULL);"
        handle_sql.insert(sql)
    handle_sql.db.close()


# 创建普通群表格
def create_group_table(database):
    handle_sql = HandleSql(database)
    table_name = handle_sql.select("SELECT name from sqlite_master where type='table' order by name")
    if ("group_data",) not in table_name:
        sql = "CREATE TABLE group_data (" \
              "group_id VARCHAR(60) NOT NULL," \
              "pin VARCHAR(60) NOT NULL);"
        handle_sql.insert(sql)
    handle_sql.db.close()


# 创建超大群表格
def create_super_group_table(database):
    handle_sql = HandleSql(database)
    table_name = handle_sql.select("SELECT name from sqlite_master where type='table' order by name")
    if ("super_group_data",) not in table_name:
        sql = "CREATE TABLE super_group_data (" \
              "super_group_id VARCHAR(60) NOT NULL," \
              "pin VARCHAR(60) NOT NULL);"
        handle_sql.insert(sql)
    handle_sql.db.close()


# 创建用户，获取pin, token
def create_user_info_main(shop_url, app_id, app_secret, merchant_id):
    handle_user = HandleUser(shop_url)
    logger.info("创建用户中……")
    # 注册用户
    res_rep = handle_user.res_uer(app_id, app_secret, merchant_id)
    try:
        # 用户pin
        pin = res_rep["data"]["pin"]
        # 用户token
        token = res_rep["data"]["userToken"]
        logger.info("用户创建成功……")
        return pin, token
    except Exception as err:
        logger.error(f"用户创建失败， 商户{shop_url}地址有误.")
        logger.error(err)
        return None


# 创建用户，获取pin, token
def create_user_info_main_new(shop_url, phone):
    handle_user = HandleUser(shop_url)
    logger.info("创建用户中……")
    # 注册用户
    res_rep = handle_user.res_user_new(phone)
    try:
        # 用户pin
        pin = res_rep["data"]["pin"]
        # 用户token
        token = res_rep["data"]["userToken"]
        logger.info("用户创建成功……")
        return pin, token, phone
    except Exception as err:
        logger.error(f"用户创建失败， 商户{shop_url}地址有误.")
        logger.error(err)
        return None


# 批量创建用户
def batch_create_user(user_nub, shop_url, merchant_id, app_id, app_secret):
    # 创建用户
    user_list = []
    for i in range(user_nub):
        data = create_user_info_main(shop_url, app_id, app_secret, merchant_id)
        if data is None:
            return None
        pin, token = data
        user_dict = {"pin": pin, "token": token}
        user_list.append(user_dict)
    return user_list


# 批量创建用户
def batch_create_user_new(user_nub, shop_url, phone_list):
    # 创建用户
    user_list = []
    for i in range(user_nub):
        data = create_user_info_main_new(shop_url, phone_list[i])
        if data is None:
            return None
        pin, token, phone = data
        user_dict = {"pin": pin, "token": token, "phone": phone}
        user_list.append(user_dict)
    return user_list


# 批量插入数据库(创建用户)
def insert_user_to_sql(user_list, database):
    create_user_table(database)
    handle_sql = HandleSql(database)
    logger.info("正在写入用户， 请稍等……")
    for user in user_list:
        my_sql = f"INSERT INTO user_data (pin, token) VALUES ('{user['pin']}', '{user['token']}')"
        handle_sql.insert(my_sql)
    handle_sql.db.close()
    logger.info("写入完成！")


# 批量插入数据库(创建用户)
def insert_user_to_sql_new(user_list, database):
    create_user_table(database)
    handle_sql = HandleSql(database)
    logger.info("正在写入用户， 请稍等……")
    for user in user_list:
        my_sql = f"INSERT INTO user_data (pin, token, phone) " \
                 f"VALUES ('{user['pin']}', '{user['token']}', '{user['phone']}')"
        handle_sql.insert(my_sql)
    handle_sql.db.close()
    logger.info("写入完成！")


# 批量插入私聊chat id
def insert_chat_id_to_sql(user_list, database):
    create_message_chat_table(database)
    handle_sql = HandleSql(database)
    for user in user_list:
        my_sql = f"INSERT INTO message_chat (chat_id, pin, apply_acc_id) " \
                 f"VALUES ('{user['chat_id']}', '{user['pin']}','{user['apply_acc_id']}');"
        handle_sql.insert(my_sql)
    handle_sql.db.close()


# 插入群聊
def insert_group_id_to_sql(group, database):
    create_group_table(database)
    handle_sql = HandleSql(database)
    my_sql = f"INSERT INTO group_data (group_id, pin) VALUES ('{group['group_id']}', '{group['pin']}');"
    handle_sql.insert(my_sql)
    handle_sql.db.close()


# 插入超大群数据
def insert_super_group_id_to_sql(group, database):
    create_super_group_table(database)
    handle_sql = HandleSql(database)
    my_sql = f"INSERT INTO super_group_data " \
             f"(super_group_id, pin) VALUES ('{group['super_group_id']}', '{group['pin']}');"
    handle_sql.insert(my_sql)
    handle_sql.db.close()


# 创建好友并同意
def handle_friend(user_url, app_id, app_secret, pin, token, apply_acc_id):
    handle_user = HandleUser(user_url)
    handle_user.create_header(app_id, app_secret, token)
    handle_user.add_friend(app_id, pin, apply_acc_id)
    handle_user_apple = HandleUser(user_url)
    res_rep = handle_user_apple.update_agree(apply_acc_id, pin)
    return res_rep


# 批量创建好友
def batch_create_friend(user_list, user_url, app_id, app_secret):
    user_len = len(user_list)
    pin = user_list[0]["pin"]
    token = user_list[0]["token"]
    for i in range(1, user_len):
        apply_acc_id = user_list[i]["pin"]
        friend_res = handle_friend(user_url, app_id, app_secret, pin, token, apply_acc_id)
        logger.info("好友状态更新：", friend_res)
        return friend_res


# 创建会话
def create_chat(user_url, app_id, app_secret, token, apply_acc_id):
    handle_user = HandleUser(user_url)
    handle_user.create_header(app_id, app_secret, token)
    res_rep = handle_user.create_chat(apply_acc_id)
    if res_rep is None:
        logger.error(f"创建私聊失败， 请检查配置！ 用户地址：{user_url}，应用id ：{app_id}， 应用密钥： {app_secret}")
    return res_rep


# 批量创建聊天(返回含有chat id与用户的列表)
def batch_create_chat(user_list, user_url, app_id, app_secret):
    # 建立会话
    user_nub = len(user_list)
    try:
        for i in range(user_nub):
            logger.info("创建会话中……")
            # 被申请人的 pin
            apply_acc_id = user_list[i]["apply_acc_id"]
            # 申请人的token
            token = user_list[i]["token"]
            chat_rep = create_chat(user_url, app_id, app_secret, token, apply_acc_id)
            if chat_rep is None:
                return None
            chat_id = chat_rep["data"]
            user_list[i]["chat_id"] = chat_id
            logger.info(f"会话创建成功！{chat_rep}")
        return user_list
    except requests.exceptions.ConnectionError:
        logger.error(f"用户接口地址{user_url}请求不通过， 请检查网络")
        return None
    except KeyError:
        logger.error(f"参数类型错误！{chat_rep}")
        return None


# 批量创建群
def batch_create_group(group_nub, chat_group_type, user_list, user_url, app_id, app_secret):
    # 处理创建者信息
    acc_id = user_list[0]["pin"]
    token = user_list[0]["token"]
    # 群成员
    apply_acc_id_list = []
    # 群成员添加
    for i in range(1, len(user_list)):
        apply_acc_id_list.append(user_list[i]["pin"])
    handle_user = HandleUser(user_url)
    handle_user.create_header(app_id, app_secret, token)
    team_chat_id = []
    try:
        # 群数量
        for i in range(group_nub):
            logger.info("创建群聊中……")
            team_res = handle_user.create_team(acc_id, chat_group_type, apply_acc_id_list)
            if team_res is None:
                logger.error(f"连接不成功， 创建群聊失败，请检查用户地址： {user_url}， 是否正确！")
                return team_res
            if team_res:
                chat_id = team_res["data"]
                team_chat_id.append(chat_id)
                logger.info("普通群创建成功！")
        return team_chat_id
    except Exception as err:
        logger.error("参数错误，创建群聊失败！")
        logger.error(err)
        return None


# 处理用户插入
def handle_insert_user(user_nub, shop_url, database, merchant_id, app_id, app_secret):
    user_list = batch_create_user(user_nub, shop_url, merchant_id, app_id, app_secret)
    if user_list is None:
        return None
    insert_user_to_sql(user_list, database)
    return True


# 处理用户插入
def handle_insert_user_new(user_nub, shop_url, database, phone_list):
    user_list = batch_create_user_new(user_nub, shop_url, phone_list)
    if user_list is None:
        return None
    insert_user_to_sql_new(user_list, database)
    return True


# 私聊插入数据库
def handle_insert_chat_id(database, chat_nub, user_url, app_id, app_secret):
    # 采用收与发分开来处理
    # n 对 n 的解决办法，以便处理 接收与发送不成正比的情况
    # 更新数据库表格的设置，增加一个单独的属性
    create_message_chat_table(database)
    # 创建数据库连接
    handle_sql = HandleSql(database)
    # 获取目前的 chat会话数量
    logger.info("获取当前的会话数……")
    select_chat_nub_sql = "SELECT COUNT(*) FROM message_chat;"
    old_chat_nub = handle_sql.select(select_chat_nub_sql)
    old_chat_nub = old_chat_nub[0][0]
    # 获取用户数
    logger.info("获取用户中……")
    select_user_sql = f"SELECT pin, token FROM user_data LIMIT {old_chat_nub * 2}, {chat_nub*2};"
    user_rep = handle_sql.select(select_user_sql)
    # 关闭数据库连接
    handle_sql.db.close()
    user_list = []
    for i in range(0, chat_nub):
        # 这个地方的逻辑问题
        user_info = dict(pin=user_rep[i][0], token=user_rep[i][1], apply_acc_id=user_rep[-i][0])
        user_list.append(user_info)
    chat_id_list = batch_create_chat(user_list, user_url, app_id, app_secret)
    if chat_id_list is None:
        return None
    logger.info("正在将数据插入数据库……")
    insert_chat_id_to_sql(chat_id_list, database)
    logger.info("数据处理完成！")
    return True


# 普通群数据插入
def handle_group_insert(user_url, app_id, app_secret, database, group_nub, group_user_nub):
    # 获取对应数量的用户
    logger.info("正在准备创建群聊需要的数据……")
    handle_sql = HandleSql(database)
    select_user_sql = f"SELECT pin, token FROM user_data LIMIT 0, {group_user_nub}"
    user_list = handle_sql.select(select_user_sql)
    handle_sql.db.close()
    user_info_list = []
    for user in user_list:
        user_info = dict(pin=user[0], token=user[1])
        user_info_list.append(user_info)
    # logger.info("创建好友中……")
    # # 创建好友关系
    # batch_create_friend(user_info_list, user_url, app_id, app_secret)
    # 批量创建群聊
    group_chat_id_list = batch_create_group(group_nub, "Group", user_info_list, user_url, app_id, app_secret)
    if group_chat_id_list is None:
        return None
    logger.info("数据插入中……")
    s = 1
    for chat_id in group_chat_id_list:
        for user in user_info_list:
            start_time = time.time()
            group_info = dict(group_id=chat_id, pin=user["pin"])
            insert_group_id_to_sql(group_info, database)
            end_time = time.time()
            if s == 1:
                all_time = group_nub * group_user_nub * (end_time - start_time)
                logger.info(f"预计需要时间 {round(all_time, 3)} 秒")
                s += 1
    logger.info("数据插入完成！")
    return True


# 超大群插入
def handle_super_group_insert(database, super_group_nub, super_group_user_nub, user_url, app_id, app_secret):
    # 获取用户
    # 获取群主信息
    logger.info("超大群数据准备中……")
    handle_sql = HandleSql(database)
    my_sql = "SELECT token,pin FROM user_data LIMIT 0, 1;"
    group_under = handle_sql.select(my_sql)
    under_token = group_under[0][0]
    under_pin = group_under[0][1]
    user_list = [{"pin": under_pin, "token": under_token}]
    my_sql = f"SELECT pin FROM user_data LIMIT 1, {super_group_user_nub};"
    user_info = handle_sql.select(my_sql)
    handle_sql.db.close()
    try:
        for user in user_info:
            user_list.append({"pin": user[0]})
        logger.info("数据处理完成，等待创建中……")
        super_group_chat_id_list = batch_create_group(super_group_nub, "SuperGroup", user_list, user_url, app_id,
                                                      app_secret)
        if super_group_chat_id_list is None:
            logger.error(f"创建群聊错误！用户地址： {user_url}， 是否正确！")
            return super_group_chat_id_list
        logger.info("数据插入中……")
        for super_group_id in super_group_chat_id_list:
            for user in user_list:
                super_group_info = dict(super_group_id=super_group_id, pin=user["pin"])
                insert_super_group_id_to_sql(super_group_info, database)
        logger.info("超大群数据处理完成！")
        return True
    except Exception as err:
        logger.error("参数类型出现错误！创建超大群错误！")
        logger.error(err)
        return None


# 创建TCP
def create_tcp(host, port):
    # 创建tcp连接
    address = (host, port)
    conn = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
    conn.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
    conn.connect(address)
    return conn


# 创建监听
def create_recv(conn):
    try:
        res_byte = conn.recv(4096)
        return res_byte
    except socket.timeout:
        return None


# 参数打包
def handle_pack(content):
    content = json.dumps(content)
    # 普通消息
    control_header = 1
    control_header_byte = control_header.to_bytes(1, byteorder="big")
    length = len(content)
    # 长度字节 int 大小为 4个字节
    len_byte = length.to_bytes(2, byteorder="big")
    # 雪花 id 字节
    worker_id = worker.get_id()
    worker_id_byte = worker_id.to_bytes(8, byteorder="big")
    # 消息体字节 大小为 length
    content_byte = bytes(content, encoding="utf-8")
    data_byte = control_header_byte + len_byte + worker_id_byte + content_byte
    return data_byte


# 协议处理
def handle_send_data(protocol, body, chat_id=""):
    data = {}
    # 会议id
    msg_id = ''.join(str(uuid.uuid4()).split('-'))
    # 时间戳
    timestamp = int(time.time())
    # 心跳协议
    if protocol == "Heart":
        data = {"status": 200}
    # 连接协议
    elif protocol == "Response":
        data = {"status": 200, "msgId": msg_id, "timestamp": timestamp, "errorMsg": "未知"}
    # 消息协议
    elif protocol == "Connect":
        token = body["token"]
        data = {"token": token, "appId": body["app_id"], "platform": "APP"}
    # 响应协议

    elif protocol == "Message":
        user = {"pin": body["pin"], "IsBot": False, "nickname": "im test", "avatar": "", "appId": body["app_id"]}
        data = {"msgId": msg_id, "timestamp": timestamp, "chatId": chat_id, "fromId": body["fromId"],
                "chatType": body["chatType"],
                "from": user, "chatMsgType": "Session", "appId": body["app_id"],
                "msgFormat": "TEXT", "noticeType": "", "body": body["message"]
                }
    elif protocol == "Notice":
        user = {"pin": body["pin"], "IsBot": False, "nickname": "im test", "avatar": "", "appId": body["app_id"]}
        data = {"msgId": msg_id, "timestamp": timestamp, "chatId": chat_id, "fromId": body["fromId"],
                "chatType": body["chatType"],
                "from": user, "chatMsgType": "Notice", "appId": body["app_id"],
                "msgFormat": "TEXT", "noticeType": "", "body": body["message"]
                }
    elif protocol == "MSG_READ":
        data = {"msgId": msg_id, "timestamp": timestamp,
                "chatId": chat_id, "fromId": body["pin"],
                "appId": body["app_id"], "chatType": body["chatType"],
                "from": {"pin": body["pin"], "IsBot": False,
                         "nickname": "test user", "avatar": "avatar", "appId": body["app_id"]},
                "chatMsgType": "Notice", "noticeType": "MSG_READ",
                "body": {"seqId": body["seq_id"], "fromId": body["pin"]}}
        protocol = "Message"
    content = {"data": data, "protocol": protocol}
    send_data = handle_pack(content)
    return send_data


# 鉴权消息
def handle_msg_connect(conn, body):
    send_data = handle_send_data("Connect", body)
    logger.info("鉴权中……")
    conn.send(send_data)


# 消息已读
def recv_msg_send(user, msg, conn):
    pin = user["pin"]
    if "false" in msg:
        msg = msg.replace("false", "False")
    if "true" in msg:
        msg = msg.replace("true", "True")
    if "null" in msg:
        msg = msg.replace("null", "''")
    msg_dict = eval(msg)
    if "seqId" in msg_dict["data"].keys():
        seq_id = msg_dict["data"]["seqId"]
    else:
        return None
    app_id = msg_dict["data"]["appId"]
    try:
        chat_type = msg_dict["data"]["chatType"]
    except KeyError:
        chat_type = "Group"
    chat_id = msg_dict["data"]["chatId"]
    body = {"pin": pin, "app_id": app_id, "chatType": chat_type,
            "seq_id": seq_id}
    send_data = handle_send_data("MSG_READ", body, chat_id)
    conn.send(send_data)


# ack 消息
def ack_send(conn, worker_id):
    # 普通消息
    control_header = 33
    control_header_byte = control_header.to_bytes(1, byteorder="big")
    # 雪花 id 字节
    worker_id_byte = worker_id.to_bytes(8, byteorder="big")
    data_byte = control_header_byte + worker_id_byte
    conn.send(data_byte)


# 普通消息
def handle_msg_send(conn, body, chat_id_list, message_nub, sleep_time=0, message_type="message"):
    s_nub = 0
    try:
        logger.info(f"开始发送消息，tcp 通道： {conn}")
        if message_type == "message":
            chat_id = chat_id_list
            for i in range(message_nub):
                send_data = handle_send_data("Message", body, chat_id)
                conn.send(send_data)
                time.sleep(sleep_time)
                s_nub += 1
        elif message_type == "group":
            for i in range(message_nub):
                for chat_id in chat_id_list:
                    send_data = handle_send_data("Message", body, chat_id)
                    conn.send(send_data)
                    s_nub += 1
                    time.sleep(sleep_time)
        logger.info(f"线程：{threading.get_ident()} 发送消息：{s_nub} 条！")
        return s_nub
    except ConnectionAbortedError or ConnectionResetError as err:
        logger.error(f"错误: 线程：{threading.get_ident()}, {conn}, {send_data}, {err}")
        return s_nub


# 处理监听
async def handle_recv(conn, user, re_nub, user_nub, time_sleep=0.05):
    s_nub = 0
    no_recv = 0
    no_res_byte = 0
    b_byte = b""
    re_nub = re_nub
    try:
        while True:
            # 将监听到的内容截取出来
            res_byte = create_recv(conn)
            if res_byte or b_byte:
                if res_byte:
                    b_byte = b_byte + res_byte
                else:
                    no_res_byte += 1
                nub = len(b_byte)
                if nub >= 11:
                    length = struct.unpack('!i', b_byte[:4])
                    length = length[0]
                    if len(b_byte) >= 44 + length:
                        msg = b_byte[44: 44 + length].decode("utf-8")
                        b_byte = b_byte[44 + length:]
                        if b_byte is None:
                            b_byte = b""
                        logger.info(f"线程：{threading.get_ident()} 收到消息：{msg}")
                        s_nub += 1
                        no_recv = 0
                        # # 消息收到 回复
                        try:
                            recv_msg_send(user, msg, conn)
                        except ConnectionAbortedError or ConnectionResetError as err:
                            logger.error(f"{err}, 收到{re_nub}条消息")
                        if s_nub == re_nub * 2:
                            logger.info(f"线程：{threading.get_ident()} 收到{re_nub}条消息，监听结束")
                            break
            else:
                logger.error(f"线程：{threading.get_ident()} 未收到消息！")
                no_recv += 1
                if no_recv == 10:
                    # 如果连续10次没有收到消息
                    # 结束接听
                    logger.error(f"线程：{threading.get_ident()}连续十次未收到消息，接听结束")
                    break
                time.sleep(time_sleep)
        logger.info(f"线程：{threading.get_ident()} 共收到消息：{s_nub}")
        return s_nub
    except Exception as err:
        logger.error(f"出现了错误：%s 线程：{threading.get_ident()} 共收到消息：{s_nub}" % err)
        logger.error(type(err))
        # raise err
        return s_nub


# 新的协议
def handle_recv_new(conn, user):
    # 接收的数量
    recv_nub = 0
    # 接收的字节数
    recv_byte_nub = 0
    # 没有接收到数据的次数
    no_res_byte_nub = 0
    # 存储字节
    all_byte = b""
    # 执行时间
    run_time = 0
    if_recv = True
    # 循环接收数据
    try:
        start_time = time.time()
        while True:
            if if_recv:
                # 接收消息
                res_byte = create_recv(conn)
                if res_byte:
                    no_res_byte_nub = 0
                    recv_byte_nub = recv_byte_nub + len(res_byte)
                    all_byte = all_byte + res_byte
                else:
                    no_res_byte_nub += 1
                    if no_res_byte_nub >= 10:
                        run_time = time.time() - start_time
                        if_recv = False
                    logger.error(f"线程：{threading.get_ident()} 未收到消息")
                    time.sleep(0.01)
                    continue
            if all_byte:
                len_nub = len(all_byte)
                if len_nub >= 11:
                    length = struct.unpack('!h', all_byte[1:3])
                    worker_id = struct.unpack('!q', all_byte[3:11])[0]
                    length = length[0]
                    if len(all_byte) >= 11 + length:
                        msg = all_byte[11: 11 + length].decode("utf-8")
                        all_byte = all_byte[11 + length:]
                        logger.info(f"线程：{threading.get_ident()} 收到消息：{msg}")
                        recv_nub += 1
                        logger.info(f"线程：{threading.get_ident()} 收到{recv_nub} 条消息")
                        try:
                            recv_msg_send(user, msg, conn)
                            ack_send(conn, worker_id)
                        except ConnectionAbortedError or ConnectionResetError as err:
                            logger.error(f"{err}, 收到{recv_nub}条消息")
            else:
                return [recv_nub, recv_byte_nub, run_time]
    except Exception as err:
        logger.error(f"%s, 收到{recv_nub}条消息" % err)
        return [recv_nub, recv_byte_nub, run_time]


# 通道处理， 鉴权， 返回 已经鉴权的连接对象列表
def handle_tcp_main(host, port, user_list, app_id):
    conn_list = []
    try:
        for user in user_list:
            conn = create_tcp(host, port)
            conn_list.append(conn)
            body = {"token": user["token"], "app_id": app_id}
            handle_msg_connect(conn, body)
        return conn_list
    except socket.gaierror or socket.timeout:
        logger.error(f"tcp 连接有误， 请检查配置文件中的 host: {host} 与 port : {port}！")
        return None


# 获取服务器配置信息
def get_server_config():
    try:
        handle_config = HandleConfig("BaseConfig.ini")
        logger.info(handle_config.get_section())
        host = handle_config.get_value("server", "host")
        port = handle_config.get_value("server", "port")
        user_url = handle_config.get_value("server", "user_url")
        shop_url = handle_config.get_value("server", "shop_url")
        merchant_id = handle_config.get_value("server", "merchant_id")
        app_id = handle_config.get_value("server", "app_id")
        app_secret = handle_config.get_value("server", "app_secret")
        logger.info(f"host: {host}, port : {port}， user url :{user_url}, shop url : {shop_url},"
                    f"merchant id : {merchant_id}, app id: {app_id}, app secret: {app_secret}")
        return host, port, user_url, shop_url, merchant_id, app_id, app_secret
    except configparser.NoSectionError as err:
        logger.error(f"配置文件信息不正确， 请参照文档正确配置配置文件！ {err}")
        return None
    except configparser.NoOptionError as err:
        logger.error(f"配置文件信息不正确， 请参照文档正确配置配置文件！ {err}")
        return None


def get_linux_config():
    try:
        handle_config = HandleConfig("LinuxBaseServer.ini")
        logger.info(handle_config.get_section())
        host = handle_config.get_value("server", "tcp_host")
        port = handle_config.get_value("server", "tcp_port")
        user_url = handle_config.get_value("server", "user_url")
        shop_url = handle_config.get_value("server", "shop_url")
        merchant_id = handle_config.get_value("server", "merchant_id")
        app_id = handle_config.get_value("server", "app_id")
        app_secret = handle_config.get_value("server", "app_secret")
        return host, port, user_url, shop_url, merchant_id, app_id, app_secret
    except configparser.NoSectionError or configparser.NoOptionError as err:
        logger.error(f"配置文件信息不正确， 请参照文档正确配置配置文件！ {err}")
        return None


# 获取私聊所需要的测试数据
def get_message_chat_data(database, user_nub, start_nub=0):
    # 获取发送需要的数据
    handle_sql = HandleSql(database)
    select_chat_id_sql = f"SELECT chat_id, pin, apply_acc_id FROM message_chat LIMIT {start_nub}, {user_nub};"
    chat_res = handle_sql.select(select_chat_id_sql)
    chat_list = []
    # 获取token
    for chat in chat_res:
        pin_sql = f"SELECT token FROM user_data WHERE pin = '{chat[1]}';"
        apple_acc_pin_sql = f"SELECT token FROM user_data WHERE pin = '{chat[2]}';"
        pin_res = handle_sql.select(pin_sql)
        apple_acc_pin = handle_sql.select(apple_acc_pin_sql)
        pin_token = pin_res[0][0]
        apple_acc_token = apple_acc_pin[0][0]
        chat_data = {"chat_id": chat[0],
                     "pin": chat[1], "token": pin_token,
                     "apply_acc_pin": chat[2], "apply_acc_token": apple_acc_token}
        chat_list.append(chat_data)
    handle_sql.db.close()
    return chat_list


# 获取群信息
def get_group_data(database, group_nub, user_nub, chat_type, start_nub=0):
    handle_sql = HandleSql(database)
    # 获取群 信息
    if chat_type == "SuperGroup":
        table_name = "super_group_data"
        group_type = "super_group_id"
    else:
        table_name = "group_data"
        group_type = "group_id"
    # 获取全部的群 id
    select_group_sql = f"SELECT distinct({group_type}) FROM {table_name};"
    group_id_res = handle_sql.select(select_group_sql)
    group_id_list = []
    for group_id in group_id_res:
        select_user_nub_sql = f"SELECT COUNT(pin) FROM {table_name};"
        group_user_nub_res = handle_sql.select(select_user_nub_sql)
        # 判断群是否满足 需要测试的人数
        if int(group_user_nub_res[0][0]) >= start_nub + user_nub:
            group_id_list.append(group_id[0])
    # 判断是否有足够的群满足
    if len(group_id_list) >= group_nub:
        group_id_list = group_id_list[:group_nub]
    else:
        logger.error(f"没有足够的群 满足测试需要，至少需要有 {group_nub} 个群，至少满足人数在 {start_nub + user_nub} 及以上")
        return None
    # 获取用户信息
    select_user_sql = f"SELECT pin FROM {table_name} WHERE " \
                      f"{group_type} = '{group_id_list[0]}' LIMIT '{start_nub}', '{user_nub}';"
    user_res = handle_sql.select(select_user_sql)
    user_list = [user[0] for user in user_res]
    user_data = []
    for pin in user_list:
        select_token_sql = f"SELECT token FROM user_data WHERE pin = '{pin}';"
        token_res = handle_sql.select(select_token_sql)
        token = token_res[0][0]
        data = {"pin": pin, "token": token}
        user_data.append(data)
    handle_sql.db.close()
    return group_id_list, user_data


# 接收消息协程处理
def handle_async(conn_list, user_list, re_nub, user_nub, q, time_sleep):
    loop = asyncio.get_event_loop()
    tasks = []
    for conn, user in zip(conn_list, user_list):
        task = loop.create_task(handle_recv(conn, user, re_nub, user_nub, time_sleep))
        tasks.append(task)
    wait_coro = asyncio.wait(tasks)
    loop.run_until_complete(wait_coro)
    recv_nub = sum([task.result() for task in tasks])
    q.put(recv_nub)
    logger.info(f"共收到数量：{recv_nub}")
    return recv_nub


# 接收线程
def handle_recv_thr(conn_list, user_list, q):
    t_list = []
    for conn, user in zip(conn_list, user_list):
        t = MyThreading(handle_recv_new, args=(conn, user))
        t_list.append(t)
    for t in t_list:
        t.setDaemon(True)
        t.start()
    for t in t_list:
        t.join()
    res_list = [t.get_result() for t in t_list]
    recv_nub = sum([t[0] for t in res_list])
    recv_byte_nub = sum([t[1] for t in res_list])
    run_time = sum([t[2] for t in res_list])
    avg_run_time = round(run_time / len(conn_list), 2)
    q.put([recv_nub, recv_byte_nub, avg_run_time])
    logger.info(f"共收到数量：{recv_nub}, 共收到的字节：{recv_byte_nub}， 平均执行时间：{avg_run_time}")
    return [recv_nub, recv_byte_nub, avg_run_time]


# 私聊线程
def message_chat_test_thread(user_list, app_id, message_nub, q, sleep_time=0):
    thr_list = []
    logger.info(f"准备执行私聊测试……")
    start_time = time.time()
    for user in user_list:
        pin = user["pin"]
        conn = user["conn"]
        chat_id = user["chat_id"]
        msg = str(int(round(time.time() * 1000)))
        body = {"pin": pin, "fromId": pin, "app_id": app_id, "chatType": "Private", "message": {"msg": msg}}
        t = MyThreading(handle_msg_send, args=(conn, body, chat_id, message_nub, sleep_time))
        thr_list.append(t)
    for t in thr_list:
        t.setDaemon(True)
        t.start()
    for t in thr_list:
        t.join()
    # 计算总共发送了多少消息
    logger.error([t.get_result() for t in thr_list])
    result = sum([t.get_result() for t in thr_list])
    run_tiem = time.time() - start_time
    q.put([result, run_tiem])


# 私聊进程
def message_chat_test_process(host, port, app_id, database, chat_nub, message_nub, sleep_time, start_nub=0):
    # 获取发送的人数
    if chat_nub < 5:
        process_nub = chat_nub
        px = 1
    else:
        process_nub = 5
        px = int(chat_nub / process_nub)
    # 测试数据准备
    # 发送者的数据
    chat_data = get_message_chat_data(database, chat_nub, start_nub=start_nub)
    send_chat_data = []
    recv_chat_data = []
    for user_info in chat_data:
        send_chat_data.append(
            {"chat_id": user_info["chat_id"],
             "pin": user_info["pin"],
             "token": user_info["token"]})
        recv_chat_data.append(
            {"chat_id": user_info["chat_id"],
             "pin": user_info["apply_acc_pin"],
             "token": user_info["apply_acc_token"]})

    conn_list = handle_tcp_main(host, port, chat_data, app_id)
    # 发送人的通道
    recv_conn_list = handle_tcp_main(host, port, recv_chat_data, app_id)
    for i in range(len(conn_list)):
        send_chat_data[i]["conn"] = conn_list[i]
    # 获取测试需要的数据
    q = multiprocessing.Queue()
    send_process_list = list()
    recv_process_list = list()
    logger.info(f"开始进行私聊消息测试，共计：{chat_nub} 个会话， 每个会话发送消息 ： {message_nub}")
    for i in range(process_nub):
        if i < process_nub - 1:
            p = Process(target=message_chat_test_thread, args=(send_chat_data[px * i: px * (i + 1)],
                                                               app_id, message_nub, q, sleep_time))
            send_process_list.append(p)
        else:
            p = Process(target=message_chat_test_thread, args=(send_chat_data[px * i:],
                                                               app_id, message_nub, q, sleep_time))
            send_process_list.append(p)
    # 接收消息 进程处理
    if chat_nub < 10:
        recv_process_nub = chat_nub
        recv_px = 1
    else:
        recv_process_nub = 10
        recv_px = int(chat_nub / recv_process_nub)
    for i in range(recv_process_nub):
        if i < recv_process_nub - 1:
            recv_p = Process(target=handle_recv_thr, args=(recv_conn_list[recv_px * i: recv_px * (i + 1)],
                                                           recv_chat_data[recv_px * i: recv_px * (i + 1)], q))
            recv_process_list.append(recv_p)
        else:
            recv_p = Process(target=handle_recv_thr, args=(recv_conn_list[recv_px * i:],
                                                           recv_chat_data[recv_px * i:], q))
            recv_process_list.append(recv_p)

    for p in send_process_list + recv_process_list:
        p.start()
    for p in send_process_list + recv_process_list:
        p.join()
    logger.info(f"私聊测试已结束，正在处理后续数据！")
    res_list = [q.get() for k in send_process_list + recv_process_list]
    send_res_list = []
    recv_res_list = []
    for res in res_list:
        if len(res) == 3:
            recv_res_list.append(res)
        elif len(res) == 2:
            send_res_list.append(res)
        else:
            pass
    send_nub = sum([k[0] for k in send_res_list])
    send_time = sum([k[1] for k in send_res_list])
    # 平均发送时间
    avg_send_time = send_time / len(send_process_list)
    # 计算接收
    logger.info(recv_res_list)
    recv_nub = sum([k[0] for k in recv_res_list])
    recv_byte_nub = sum([k[1] for k in recv_res_list])
    recv_time = sum([k[2] for k in recv_res_list])
    avg_recv_time = recv_time / len(recv_res_list)
    for conn in conn_list:
        conn.close()
    return send_nub, recv_nub, recv_byte_nub, round(avg_send_time, 2), round(avg_recv_time, 2)


# 群聊
def group_test_thread(user_list, group_id_list, app_id, q, message_nub, sleep_time, chat_type="Group"):
    thr_list = []
    start_time = time.time()
    for user in user_list:
        pin = user["pin"]
        conn = user["conn"]
        msg = str(int(round(time.time() * 1000)))
        body = {"pin": pin, "fromId": pin, "app_id": app_id, "chatType": chat_type, "message": {"msg": msg}}
        t = MyThreading(handle_msg_send, args=(conn, body, group_id_list, message_nub, sleep_time, "group"))
        thr_list.append(t)
    for t in thr_list:
        t.setDaemon(True)
        t.start()
    for t in thr_list:
        t.join()
    # 计算总共发送了多少消息
    result = sum([t.get_result() for t in thr_list])
    # 运行时间
    run_time = time.time() - start_time
    q.put([result, run_time])


# 群聊测试
def group_test_process(host, port, app_id, database, group_nub, send_nub, recv_nub, message_nub, sleep_time, chat_type,
                       start_nub=0):
    # 获取发送的人数
    if send_nub < 5:
        process_nub = send_nub
        px = 1
    else:
        process_nub = 5
        px = int(send_nub / process_nub)
    user_nub = send_nub + recv_nub
    # 获取参数
    get_group_res = get_group_data(database, group_nub, user_nub, chat_type, start_nub=start_nub)
    if get_group_res is None:
        return None
    group_id_list, user_data = get_group_res
    logger.info(f"用户信息获取成功 ： 用户信息： {user_data}, 群信息： {group_id_list}")
    conn_list = handle_tcp_main(host, port, user_data, app_id)
    logger.info("通道建立完成")
    time.sleep(1)
    for i in range(len(conn_list)):
        user_data[i]["conn"] = conn_list[i]
    send_user_list = user_data[:send_nub]
    recv_user_list = user_data[send_nub:]
    # 获取接收消息的 TCP 通道
    recv_user_conn = [recv_user["conn"] for recv_user in recv_user_list]
    q = multiprocessing.Queue()
    send_process_list = list()
    recv_process_list = list()
    logger.info(f"开始进行私聊消息测试，{send_nub} 人发送消息， {recv_nub} 接收消息，每人发送消息 ： {message_nub}")
    for i in range(process_nub):
        if i < process_nub - 1:
            p = Process(target=group_test_thread, args=(send_user_list[px * i: px * (i + 1)],
                                                        group_id_list, app_id, q, message_nub, sleep_time,
                                                        chat_type))
            send_process_list.append(p)
        else:
            p = Process(target=group_test_thread, args=(send_user_list[px * i:],
                                                        group_id_list, app_id, q, message_nub, sleep_time,
                                                        chat_type))
            send_process_list.append(p)
    # 接收消息 进程处理
    if recv_nub != 0:
        if recv_nub < 10:
            recv_process_nub = recv_nub
            recv_px = 1
        else:
            recv_process_nub = 10
            recv_px = int(recv_nub / recv_process_nub)
        for i in range(recv_process_nub):
            if i < recv_process_nub - 1:
                recv_p = Process(target=handle_recv_thr,
                                 args=(recv_user_conn[recv_px * i: recv_px * (i + 1)], recv_user_list,
                                       q))
                recv_process_list.append(recv_p)
            else:
                recv_p = Process(target=handle_recv_thr,
                                 args=(recv_user_conn[recv_px * i:], recv_user_list,
                                       q))
                recv_process_list.append(recv_p)

    for p in send_process_list + recv_process_list:
        p.start()
    for p in send_process_list + recv_process_list:
        p.join()
    res_list = [q.get() for k in send_process_list + recv_process_list]
    send_res_list = []
    recv_res_list = []
    for res in res_list:
        if len(res) == 3:
            recv_res_list.append(res)
        elif len(res) == 2:
            send_res_list.append(res)
        else:
            pass
    if send_nub != 0:
        send_nub = sum([p[0] for p in send_res_list])
        send_time = sum([p[1] for p in send_res_list])
        avg_send_time = send_time / len(send_res_list)
    else:
        send_nub = 10001
        avg_send_time = 10001
    # 处理接收数据
    recv_nub = sum([p[0] for p in recv_res_list])
    recv_byte_nub = sum([p[1] for p in recv_res_list])
    recv_time = sum([p[2] for p in recv_res_list])
    avg_recv_time = recv_time / len(recv_res_list)
    logger.info("测试结束，正在处理后续数据！")
    time.sleep(30)
    for conn in conn_list:
        conn.close()
    return send_nub, recv_nub, recv_byte_nub, round(avg_send_time, 2), round(avg_recv_time, 2)


# 获取创建类执行参数
def get_create_config():
    try:
        handle_config = HandleConfig("TestMessageConfig.ini")
        # 创建用户信息
        create_user_config = {}
        create_user = handle_config.get_value("CreateUser", "create_user")
        if create_user.upper() == "TRUE":
            user_nub = handle_config.get_value("CreateUser", "user_nub")
            create_user_config["user_nub"] = user_nub
            create_user_config["create_user"] = True
        else:
            create_user_config["create_user"] = False
        # 创建私聊会话信息
        create_message_chat_config = {}
        create_message_chat = handle_config.get_value("CreateMessageChat", "create_chat")
        if create_message_chat.upper() == "TRUE":
            chat_nub = handle_config.get_value("CreateMessageChat", "chat_nub")
            create_message_chat_config["chat_nub"] = chat_nub
            create_message_chat_config["create_chat"] = True
        else:
            create_message_chat_config["create_chat"] = False
        # 创建群聊信息
        create_group_config = {}
        create_group = handle_config.get_value("CreateGroup", "create_group")
        if create_group.upper() == "TRUE":
            group_nub = handle_config.get_value("CreateGroup", "group_nub")
            create_group_config["group_nub"] = group_nub
            group_user_nub = handle_config.get_value("CreateGroup", "group_user_nub")
            create_group_config["group_user_nub"] = group_user_nub
            create_group_config["create_group"] = True
        else:
            create_group_config["create_group"] = False
        # 创建超大群信息
        create_super_group_config = {}
        create_super_group = handle_config.get_value("CreateSuperGroup", "create_super_group")
        if create_super_group.upper() == "TRUE":
            super_group_user_nub = handle_config.get_value("CreateSuperGroup", "super_group_user_nub")
            create_super_group_config["super_group_user_nub"] = super_group_user_nub
            super_group_nub = handle_config.get_value("CreateSuperGroup", "super_group_nub")
            create_super_group_config["group_user_nub"] = super_group_nub
            create_super_group_config["create_super_group"] = True
        else:
            create_super_group_config["create_super_group"] = False
        return create_user_config, create_message_chat_config, create_group_config, create_super_group_config
    except configparser.NoSectionError as err:
        logger.error(f"测试配置文件信息不正确， 请参照文档正确配置配置文件！ {err}")
        return None
    except configparser.NoOptionError as err:
        logger.error(f"测试配置文件信息不正确， 请参照文档正确配置配置文件！ {err}")
        return None


# 获取测试类执行参数
def get_test_config():
    try:
        test_config_dict = {}
        handle_config = HandleConfig("TestMessageConfig.ini")
        # 判断是否需要进行私聊测试
        message_chat_test = handle_config.get_value("MessageChatTest", "message_chat_test")
        if message_chat_test.upper() == "TRUE":
            test_config_dict["test_type"] = "MessageChatTest"
            chat_nub = handle_config.get_value("MessageChatTest", "chat_nub")
            message_nub = handle_config.get_value("MessageChatTest", "message_nub")
            if_sleep = handle_config.get_value("MessageChatTest", "if_sleep")
            sleep_time = handle_config.get_value("MessageChatTest", "sleep_time")
            data = dict(chat_nub=chat_nub,
                        message_nub=message_nub, if_sleep=if_sleep, sleep_time=sleep_time)
            test_config_dict["test_data"] = data
            return test_config_dict
        # 判断是否需要进行群聊测试
        group_test = handle_config.get_value("GroupTest", "group_test")
        if group_test.upper() == "TRUE":
            test_config_dict["test_type"] = "GroupTest"
            # 每个群的发消息人数
            group_send_nub = handle_config.get_value("GroupTest", "group_send_nub")
            # 每个群的接收消息的人数
            group_recv_nub = handle_config.get_value("GroupTest", "group_recv_nub")
            # 群数量
            group_nub = handle_config.get_value("GroupTest", "group_nub")
            # 每个群每人发送消息的总量
            message_nub = handle_config.get_value("GroupTest", "message_nub")
            # 发送消息是否需要等待，如果开启则需要设置 等待时间 sleep_time.
            if_sleep = handle_config.get_value("GroupTest", "if_sleep")
            # 等待时间，单位秒。如sleep_time =0.5 ，则用户向群发送一条消息后需要等待0.5秒，才会继续发送消息
            sleep_time = handle_config.get_value("GroupTest", "sleep_time")
            data = dict(group_send_nub=group_send_nub, group_recv_nub=group_recv_nub, group_nub=group_nub,
                        message_nub=message_nub, if_sleep=if_sleep, sleep_time=sleep_time)
            test_config_dict["test_data"] = data
            return test_config_dict
        super_group_test = handle_config.get_value("SuperGroupTest", "super_group_test")
        if super_group_test.upper() == "TRUE":
            test_config_dict["test_type"] = "SuperGroupTest"
            # 发送消息的人数
            super_group_send_nub = handle_config.get_value("SuperGroupTest", "super_group_send_nub")
            # 接收消息的人数
            super_group_recv_nub = handle_config.get_value("SuperGroupTest", "super_group_recv_nub")
            # 群数量
            super_group_nub = handle_config.get_value("SuperGroupTest", "super_group_nub")
            # 每个群每人发送消息的总量
            message_nub = handle_config.get_value("SuperGroupTest", "message_nub")
            # 是否消息等待
            if_sleep = handle_config.get_value("SuperGroupTest", "if_sleep")
            # 等待时间，单位秒。如sleep_time =0.5 ，则用户向群发送一条消息后需要等待0.5秒，才会继续发送消息
            sleep_time = handle_config.get_value("SuperGroupTest", "sleep_time")
            data = dict(super_group_send_nub=super_group_send_nub, super_group_recv_nub=super_group_recv_nub,
                        super_group_nub=super_group_nub,
                        message_nub=message_nub, if_sleep=if_sleep, sleep_time=sleep_time)
            test_config_dict["test_data"] = data
            return test_config_dict
    except configparser.NoSectionError as err:
        logger.error(f"测试配置文件信息不正确， 请参照文档正确配置配置文件！ {err}")
        return None
    except configparser.NoOptionError as err:
        logger.error(f"测试配置文件信息不正确， 请参照文档正确配置配置文件！ {err}")
        return None


def create_user_main(create_user_config, shop_url, database, merchant_id, app_id, app_secret):
    logger.info("配置文件：需要创建用户。")
    user_nub = create_user_config["user_nub"]
    # 创建用户
    ass = handle_insert_user(int(user_nub), shop_url, database, merchant_id, app_id, app_secret)
    if ass is None:
        logger.error("用户创建失败！请检查配置信息！")
        return None
    else:
        logger.info("用户创建完成")
        return True


def create_user_main_new(create_user_config, shop_url, database, phone_start):
    create_user_table(database)
    logger.info("配置文件：需要创建用户。")
    user_nub = create_user_config["user_nub"]
    phone_list = []
    handle_sql = HandleSql(database)
    sql_count = "SELECT COUNT(*) FROM user_data;"
    count_nub = handle_sql.select(sql_count)
    if count_nub[0][0] == 0:
        phone_start = int(f"{int(phone_start)}" + "10000000")
    else:
        sql = "SELECT phone FROM user_data ORDER BY id DESC LIMIT 1;"
        end_phone = handle_sql.select(sql)
        phone_start = int(end_phone[0][0])
    handle_sql.db.close()
    for i in range(phone_start + 1, phone_start + int(user_nub) + 1):
        phone_list.append(str(i))
    # 创建用户
    ass = handle_insert_user_new(int(user_nub), shop_url, database, phone_list)
    if ass is None:
        logger.error("用户创建失败！请检查配置信息！")
        return None
    else:
        logger.info("用户创建完成")
        return True


def create_chat_main(database, create_message_chat_config, user_url, app_id, app_secret):
    # 获取数据库中目前的用户数量
    db_user_nub_sql = "SELECT COUNT(*) FROM user_data;"
    handle_sql = HandleSql(database)
    db_user_nub = handle_sql.select(db_user_nub_sql)
    handle_sql.db.close()
    db_user_nub = int(db_user_nub[0][0])
    logger.info("配置文件：需要创建私聊。")
    chat_nub = int(create_message_chat_config["chat_nub"])
    # 检查是否有足够数量的用户
    # 一个私聊是2个用户
    if chat_nub * 2 <= db_user_nub:
        ass = handle_insert_chat_id(database, chat_nub, user_url, app_id, app_secret)
        if ass is None:
            logger.error("参数出现异常，测试结束！")
            return None
        else:
            logger.info("私聊会话创建完毕")
            return True
    else:
        logger.error(f"用户数量不足以创建私聊， 当前用户量： {db_user_nub}个，需要用户数量： {chat_nub*2} ")
        return None


def create_group_main(database, create_group_config, user_url, app_id, app_secret):
    # 获取数据库中目前的用户数量
    db_user_nub_sql = "SELECT COUNT(*) FROM user_data;"
    handle_sql = HandleSql(database)
    db_user_nub = handle_sql.select(db_user_nub_sql)
    handle_sql.db.close()
    db_user_nub = int(db_user_nub[0][0])
    logger.info("配置文件：需要创建群聊。")
    group_nub = int(create_group_config["group_nub"])
    group_user_nub = int(create_group_config["group_user_nub"])
    # 需要检查用户数量是否足够
    if group_user_nub <= db_user_nub:
        ass = handle_group_insert(user_url, app_id, app_secret, database,
                                  group_nub, group_user_nub)
        if ass is None:
            logger.error("参数出现异常，测试结束！")
        else:
            logger.info("群聊创建成功！")
            return True
    else:
        logger.error(f"用户数量不足以创建群聊， 当前用户量： {db_user_nub}个，需要用户数量： {group_user_nub} ")


def create_super_group_main(database, create_super_group_config, user_url, app_id, app_secret):
    # 获取数据库中目前的用户数量
    db_user_nub_sql = "SELECT COUNT(*) FROM user_data;"
    handle_sql = HandleSql(database)
    db_user_nub = handle_sql.select(db_user_nub_sql)
    handle_sql.db.close()
    db_user_nub = int(db_user_nub[0][0])
    logger.info("配置文件：需要创建超大群聊。")
    super_group_user_nub = int(create_super_group_config["super_group_user_nub"])
    super_group_nub = int(create_super_group_config["group_user_nub"])
    logger.info(type(super_group_user_nub))
    if super_group_user_nub <= db_user_nub:
        ass = handle_super_group_insert(database, super_group_nub,
                                        super_group_user_nub, user_url, app_id, app_secret)
        if ass is None:
            logger.error("参数异常， 测试结束！")
            return None
        else:
            logger.info("创建超大群聊完成")
            return True
    else:
        logger.error(f"用户数量不足以创建超大群， 当前用户量： {db_user_nub}个，需要用户数量： {super_group_user_nub} ")


def message_chat_test_main(database, test_config_dict, host, port, app_id, test_type, start_nub=0):
    logger.info("配置文件：进行私聊测试。")
    test_data = test_config_dict["test_data"]
    chat_nub = int(test_data["chat_nub"])
    message_nub = int(test_data["message_nub"])
    if_sleep = test_data["if_sleep"]
    if if_sleep.upper() == "TRUE":
        sleep_time = float(test_data["sleep_time"])
    else:
        sleep_time = 0
    # 获取当前的会话数
    select_chat_nub_sql = "SELECT COUNT(chat_id) FROM message_chat;"
    handle_sql = HandleSql(database)
    db_chat_nub = handle_sql.select(select_chat_nub_sql)
    handle_sql.db.close()
    db_chat_nub = int(db_chat_nub[0][0])
    if chat_nub > db_chat_nub - start_nub:
        logger.error(f"聊天会话不足， 请添加足量的私聊会话， 目前有会话： {db_chat_nub}, 需要会话：{chat_nub}")
        return None
    # 调用执行
    private_res = message_chat_test_process(host, port, app_id, database, chat_nub,
                                            message_nub, sleep_time, start_nub=start_nub)
    if private_res is None:
        logger.error("数据不足！")
        return None
    all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time = private_res
    handle_file(project_path, test_type, chat_nub,
                chat_nub, message_nub, 0, all_send_nub, avg_send_time)
    logger.info(f"发送时间： {avg_send_time} ,共发送消息： {all_send_nub}, "
                f"接收消息时间：{avg_recv_time}，共接收消息 ： {all_recv_nub}, 接收文件中大小： {all_recv_byte_nub}， "
                f"每秒发送消息速度： {round(all_send_nub/avg_send_time, 2)}, "
                f"每秒接收消息速度： {round(all_recv_nub/avg_recv_time, 2)}")
    return all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time


def group_test_main(database, test_config_dict, host, port, app_id, test_type, start_nub=0):
    logger.info("配置文件：进行群聊测试。")
    test_data = test_config_dict["test_data"]
    group_send_nub = int(test_data["group_send_nub"])
    group_recv_nub = int(test_data["group_recv_nub"])
    group_nub = int(test_data["group_nub"])
    message_nub = int(test_data["message_nub"])
    if_sleep = test_data["if_sleep"]
    if if_sleep.upper() == "TRUE":
        sleep_time = float(test_data["sleep_time"])
    else:
        sleep_time = 0
    # 获取当前的会话数
    select_chat_nub_sql = "SELECT COUNT(*) FROM (SELECT * FROM group_data GROUP BY group_id);"
    handle_sql = HandleSql(database)
    db_group_nub = handle_sql.select(select_chat_nub_sql)
    handle_sql.db.close()
    db_group_nub = int(db_group_nub[0][0])
    if group_nub > db_group_nub:
        logger.error(f"群聊不足， 请添加足量的群聊， 目前有群聊： {db_group_nub}, 需要群聊：{group_nub}")
        return None
    # 调用执行
    group_process_res = group_test_process(host, port, app_id, database, group_nub,
                                           group_send_nub, group_recv_nub,
                                           message_nub, sleep_time, "Group", start_nub=start_nub)
    if group_process_res is None:
        logger.error("数据不足！")
        return None
    all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time = group_process_res
    if group_send_nub == 0:
        group_send_nub = 10001
    handle_file(project_path, test_type, group_send_nub, group_recv_nub,
                message_nub, group_nub, all_send_nub, avg_send_time)
    logger.info(f"发送消息时间： {avg_send_time} ,共发送消息： {all_send_nub}, "
                f"接收消息时间：{avg_recv_time}， 共接收消息 ： {all_recv_nub},  接收文件总大小： {all_recv_byte_nub}， "
                f"每秒发送消息速度： {round(all_send_nub/avg_send_time, 2)}, "
                f"每秒接收消息速度： {round(all_recv_nub/avg_recv_time, 2)}")
    return all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time


def super_group_test_main(database, test_config_dict, host, port, app_id, test_type, start_nub=0):
    logger.info("配置文件：进行超大测试。")
    test_data = test_config_dict["test_data"]
    super_group_send_nub = int(test_data["super_group_send_nub"])
    super_group_recv_nub = int(test_data["super_group_recv_nub"])
    super_group_nub = int(test_data["super_group_nub"])
    message_nub = int(test_data["message_nub"])
    if_sleep = test_data["if_sleep"]
    if if_sleep.upper() == "TRUE":
        sleep_time = float(test_data["sleep_time"])
    else:
        sleep_time = 0
    # 获取当前的会话数
    select_chat_nub_sql = "SELECT COUNT(*) FROM (SELECT * FROM super_group_data GROUP BY super_group_id);"
    handle_sql = HandleSql(database)
    db_super_group_nub = handle_sql.select(select_chat_nub_sql)
    handle_sql.db.close()
    db_super_group_nub = int(db_super_group_nub[0][0])
    if super_group_nub > db_super_group_nub:
        logger.error(f"超大群聊不足， 请添加足量的群聊， 目前有群聊： {db_super_group_nub}, 需要群聊：{super_group_nub}")
        return None
    # 调用执行
    group_process_res = group_test_process(host, port,
                                           app_id,
                                           database,
                                           super_group_nub,
                                           super_group_send_nub,
                                           super_group_recv_nub,
                                           message_nub,
                                           sleep_time,
                                           "SuperGroup", start_nub=start_nub)
    if group_process_res is None:
        logger.error("数据不足！")
        return None
    all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time = group_process_res
    handle_file(project_path, test_type, super_group_send_nub, super_group_recv_nub,
                message_nub, super_group_nub, all_send_nub, avg_send_time)
    logger.info(
        f"发送消息时间： {avg_send_time} ,共发送消息： {all_send_nub}, 接收消息时间：{avg_recv_time}， "
        f"共接收消息 ： {all_recv_nub}, 接收文件大小：{all_recv_byte_nub}, "
        f"每秒发送消息速度： {round(all_send_nub/avg_send_time, 2)}, 每秒接收消息速度： {round(all_recv_nub/avg_recv_time, 2)}")
    return all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time


# 主函数
def run(start_nub=0, data_base_name="send_message.db", phone_start="139"):
    # 获取基础配置
    # 数据库信息
    database = project_path + "/config/" + data_base_name
    # 系统配置
    server_data = get_server_config()
    if not server_data:
        return None
    host, port, user_url, shop_url, merchant_id, app_id, app_secret = server_data
    port = int(port)
    # 获取创建参数
    create_config = get_create_config()
    if create_config:
        if_test = True
        create_user_config, create_message_chat_config, create_group_config, create_super_group_config = create_config
        # 创建用户
        if create_user_config["create_user"]:
            if_test = False
            if data_base_name == "send_message.db":
                create_user_main(create_user_config, shop_url, database, merchant_id, app_id, app_secret)
            else:
                handle_config = HandleConfig("BaseConfig.ini")
                shop_user_url = handle_config.get_value("server", "shop_user_url")
                create_user_main_new(create_user_config, shop_user_url, database, phone_start)
        # 创建私聊
        if create_message_chat_config["create_chat"]:
            if_test = False
            create_chat_main(database, create_message_chat_config, user_url, app_id, app_secret)
        # 创建群聊
        if create_group_config["create_group"]:
            if_test = False
            create_group_main(database, create_group_config, user_url, app_id, app_secret)
        # 创建超大群聊
        if create_super_group_config["create_super_group"]:
            if_test = False
            create_super_group_main(database, create_super_group_config, user_url, app_id, app_secret)
        if if_test is False:
            return True
    # 获取测试数据
    logger.info("开始获取测试数据！")
    test_config_dict = get_test_config()
    if test_config_dict:
        test_type = test_config_dict["test_type"]
        # 私聊测试
        if test_type == "MessageChatTest":
            private_res = message_chat_test_main(database, test_config_dict, host, port, app_id, test_type,
                                                 start_nub=start_nub)
            if private_res is None:
                return None
            all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time = private_res
            return all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time
        # 普通群聊测试
        elif test_type == "GroupTest":
            private_res = group_test_main(database, test_config_dict, host, port, app_id, test_type,
                                          start_nub=start_nub)
            if private_res is None:
                return None
            all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time = private_res
            return all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time
        # 超级大群测试
        elif test_type == "SuperGroupTest":
            private_res = super_group_test_main(database, test_config_dict, host, port, app_id, test_type, start_nub)
            if private_res is None:
                return None
            all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time = private_res
            return all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time
    else:
        logger.error("没有需要执行的测试程序， 请检查配置文件是否正确！")
        return None


def run_linux(start_nub=0, data_base_name="send_message.db", phone_start="139"):
    database = project_path + "/config/" + data_base_name
    # 基础配置获取
    server_data = get_linux_config()
    if not server_data:
        return None
    host, port, user_url, shop_url, merchant_id, app_id, app_secret = server_data
    port = int(port)
    # 执行配置获取
    handle_config = HandleConfig("LinuxTestConfig.ini")
    create_test = handle_config.get_value("TestConfig", "create_test")
    if create_test == "1":
        create_type = handle_config.get_value("TestConfig", "create_test")
        # 创建用户
        if create_type == "1":
            create_user_nub = int(handle_config.get_value("TestConfig", "create_user_nub"))
            create_user_config = dict(user_nub=create_user_nub)
            if data_base_name == "send_message.db":
                res = create_user_main(create_user_config, shop_url, database, merchant_id, app_id, app_secret)
            else:
                handle_config = HandleConfig("BaseConfig.ini")
                shop_user_url = handle_config.get_value("server", "shop_user_url")
                res = create_user_main_new(create_user_config, shop_user_url, database, phone_start)
            if res is None:
                return None
            all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time = res
            return all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time
        # 创建私聊
        elif create_type == "2":
            create_private_nub = int(handle_config.get_value("TestConfig", "create_private_nub"))
            create_message_chat_config = dict(chat_nub=create_private_nub)
            res = create_chat_main(database, create_message_chat_config, user_url, app_id, app_secret)
            if res is None:
                return None
            all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time = res
            return all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time
        # 创建群聊
        elif create_type == "3":
            group_nub = int(handle_config.get_value("TestConfig", "group_nub"))
            group_user_nub = int(handle_config.get_value("TestConfig", "group_user_nub"))
            create_group_config = dict(group_nub=group_nub, group_user_nub=group_user_nub)
            res = create_group_main(database, create_group_config, user_url, app_id, app_secret)
            if res is None:
                return None
            all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time = res
            return all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time
        # 创建超级大群
        elif create_type == "4":
            super_group_nub = int(handle_config.get_value("TestConfig", "super_group_nub"))
            super_group_user_nub = int(handle_config.get_value("TestConfig", "super_group_user_nub"))
            create_super_group_config = dict(super_group_nub=super_group_nub, super_group_user_nub=super_group_user_nub)
            res = create_super_group_main(database, create_super_group_config, user_url, app_id, app_secret)
            if res is None:
                return None
            all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time = res
            return all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time
        else:
            pass
    elif create_test == "2":
        test_type = handle_config.get_value("TestConfig", "test_type")
        # 私聊测试
        if test_type == "1":
            private_message_nub = int(handle_config.get_value("TestConfig", "private_message_nub"))
            message_nub = int(handle_config.get_value("TestConfig", "message_nub"))
            time_sleep = float(handle_config.get_value("TestConfig", "time_sleep"))
            test_data = dict(chat_nub=private_message_nub, message_nub=message_nub, if_sleep="true",
                             sleep_time=time_sleep)
            test_config_dict = {"test_data": test_data}

            res = message_chat_test_main(database, test_config_dict, host, port, app_id, test_type, start_nub=start_nub)
            if res is None:
                return None
            all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time = res
            return all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time
        # 普通群聊测试
        elif test_type == "2":
            group_nub = int(handle_config.get_value("TestConfig", "group_nub"))
            send_user_nub = int(handle_config.get_value("TestConfig", "send_user_nub"))
            recv_user_nub = int(handle_config.get_value("TestConfig", "recv_user_nub"))
            send_message_nub = int(handle_config.get_value("TestConfig", "send_message_nub"))
            time_sleep = float(handle_config.get_value("TestConfig", "time_sleep"))
            test_data = dict(group_send_nub=send_user_nub, group_recv_nub=recv_user_nub, group_nub=group_nub,
                             message_nub=send_message_nub, if_sleep="true", sleep_time=time_sleep)
            test_config_dict = {"test_data": test_data}
            res = group_test_main(database, test_config_dict, host, port, app_id, test_type, start_nub)
            if res is None:
                return None
            all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time = res
            return all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time
        # 超级大群测试
        elif test_type == "3":
            super_group_nub = int(handle_config.get_value("TestConfig", "super_group_nub"))
            send_user_nub = int(handle_config.get_value("TestConfig", "send_user_nub"))
            recv_user_nub = int(handle_config.get_value("TestConfig", "recv_user_nub"))
            send_message_nub = int(handle_config.get_value("TestConfig", "send_message_nub"))
            time_sleep = float(handle_config.get_value("TestConfig", "time_sleep"))
            test_data = dict(super_group_send_nub=send_user_nub, super_group_recv_nub=recv_user_nub,
                             super_group_nub=super_group_nub,
                             message_nub=send_message_nub, if_sleep="true", sleep_time=time_sleep)
            test_config_dict = {"test_data": test_data}
            res = super_group_test_main(database, test_config_dict, host, port, app_id, test_type, start_nub)
            if res is None:
                return None
            all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time = res
            return all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time

    else:
        return None


def main(start_nub=0, database="send_message.db", phone_start="130"):
    if sys.platform == "win32" or sys.platform == "win64":
        logger.info("windows")
        res = run(start_nub, database, phone_start)
        if res is None:
            return None
        elif res is True:
            return True
        else:
            all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time = res
            with open(project_path + "/test_file/test_ass.ini", "w", encoding="utf-8") as f:
                string = f"""{all_send_nub},{all_recv_nub},{all_recv_byte_nub},{avg_send_time},{avg_recv_time}"""
                f.write(string)
                f.close()
    else:
        logger.info("Linux")
        res = run_linux(start_nub, database, phone_start)
        if res is None:
            return None
        elif res is True:
            return True
        else:
            all_send_nub, all_recv_nub, all_recv_byte_nub, avg_send_time, avg_recv_time = res
            with open(project_path + "/test_file/test_ass.ini", "w", encoding="utf-8") as f:
                string = f"""{all_send_nub},{all_recv_nub},{all_recv_byte_nub},{avg_send_time},{avg_recv_time}"""
                f.write(string)
                f.close()


if __name__ == "__main__":
    main(database="new_send_message.db")
